//
//  JXLUserAccountViewModel.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/9/24.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//

import UIKit

class JXLUserAccountViewModel: NSObject {

    //单例访问对象，用户模型对象全局共享
    static let sharedUserAccountViewModel = JXLUserAccountViewModel()
    
    //沙盒路径存储的用户模型
    var userAccount: JXLUserAccount? {
        //从沙盒中提取
        return JXLUserAccount.loadUserAccount()
    }
    
    //判断是否登录操作
    var isLogin: Bool {
        return accessToken != nil
    }
    
    //判断access Token是否过期
    var accessToken: String? {
        //1,获取access Token
        let token = userAccount?.access_token
        
        //2,获取过期时间对象
        let expiresDate = userAccount?.expiresDate
        //如果access Token有值，则进入判断是否过期
        if let t = token {
            
            if expiresDate?.compare(Date()) == .orderedDescending {
            return t
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    //相关的网络请求，从JXLOAuthViewController中抽取过来
    //通过code获取accessToken
    func requestAccessToken(code: String, callBack: @escaping (Bool) -> ()) {
        JXLNetworkingTools.sharedTools.requestAccesstoken(code: code) { (response, error) in
            if error != nil {
                print("网络请求异常\(error)")
                callBack(false)
            }
            
            //代码执行到此，请求成功
            guard let dict = response as? [String: Any] else {
                print("不是正确的字典格式")
                callBack(false)
                return
            }
            
            let userAccount = JXLUserAccount(dict: dict)
            print(userAccount.access_token)
            
            self.requestuserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    
    //  根据accesskon和用户id获取用户信息
   private func requestuserInfo(userAccount: JXLUserAccount, callBack: @escaping (Bool) -> ()) {
        JXLNetworkingTools.sharedTools.requestUserInfo(access_token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            if error != nil {
                print("网络请求异常")
                print(error)
                callBack(false)
                return
            }
            
            //代码执行到此，表示请求成功
            guard let dict = response as? [String: Any] else {
                print("不是正确的字典格式")
                callBack(false)
                return
            }
            
            let name = dict["name"]
            let avatr_large = dict["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatr_large as? String
            
            print(userAccount.name)
            print(userAccount.avatar_large)
            //代码执行到此，表示登录成功
            userAccount.saveUserAccount()
            callBack(true)
            
        }
    }

    
}
